package com.cb.controller;
import com.cb.domain.User;
import com.cb.mapper.UserMapper;
import com.cb.service.UserService;
import entity.PageResult;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * 用户登录和注销Controller
 */
@Controller
public class UserController {
    @RequestMapping("/toMainPage")
    public String toMainPage() {
        return "main";
    }

    //注入userService
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    /*
   用户登录
    */
    @RequestMapping("/to_login")
    public String to_login() {
        return "/login";
    }

    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        try {
            User u = userService.login(user);
            /*
            用户账号和密码是否查询出用户信息
                是：将用户信息存入Session，并跳转到后台首页
                否：Request域中添加提示信息，并转发到登录页面
             */
            if (u == null) {
                request.setAttribute("msg", "用户名或密码错误");
                return "forward:to_login";
            }
            //<!--获取用户的状态--> 0:可登录 1：禁用
            else if (u.getStatus() == 1) {
                request.setAttribute("msg", "账号异常，请联系管理员");
                return "forward:to_login";
            } else {
                request.getSession().setAttribute("USER_SESSION", u);
                return "redirect:/admin/main.jsp";
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "forward:to_login";
        }
    }

    /*
    注销登录
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            //销毁Session
            session.invalidate();
            return "forward:to_login";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "forward:to_login";
        }
    }

    /*
    注册功能
     */
    @RequestMapping("/to_register")
    public String to_register() {
        return "/register";
    }

    @RequestMapping("/register")
    public String register(User user, HttpServletRequest request,
                           @RequestParam("name") String name,
                           @RequestParam("password") String password,
                           @RequestParam("password2") String password2,
                           @RequestParam("email") String email,
                           Model model) {
        User u = new User();
        u.setName(name);
        u.setPassword(password);
        u.setPassword2(password2);
        u.setEmail(email);
        u.setRole("USER");
        u.setStatus(0);

        //验证用户名
        if (u.getName() == "") {
            model.addAttribute("msg", "用户名不能为空！");
            return "forward:to_register";
        }
        //验证邮箱
        else if (u.getEmail() == "") {
            model.addAttribute("msg", "邮箱不能为空！");
            return "forward:to_register";
        }
        //验证密码是否为空
        else if (u.getPassword() == "") {
            model.addAttribute("msg", "密码不能为空！");
            return "forward:to_register";
        }
        //验证邮箱地址
        else if (!u.getEmail().matches
                ("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$")) {
            model.addAttribute("msg", "邮箱格式填写不正确！");
            return "forward:to_register";
        }
        //验证邮箱是否已被注册
        else if (userMapper.findUserByEmail(email) != null) {
            model.addAttribute("msg", "该邮箱已被注册，请登录！");
            return "forward:to_register";
        }
        else if (!u.getPassword().equals(u.getPassword2()) ) {
            model.addAttribute("msg","两次输入的密码不一致！");
            return "forward:to_register";
        }
        //通过验证
        else {
            try {
                //进行注册操作，把信息插入数据库
                userService.register(u);
                User user1 = userService.login(user);
                if (user1 != null) {
                    return "forward:to_login";
                } else {
                    request.setAttribute("msg", "注册失败！");
                    return "forward:to_register";
                }

            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("msg", "系统错误");
                return "forward:to_register";
            }
        }
    }


    /**
     * 分页查询所有用户信息
     *
     * @param user     查询的条件封装到user中
     * @param pageNum  数据列表的当前页码
     * @param pageSize 数据列表1页展示多少条数据
     */
    @RequestMapping("/users")
    public ModelAndView searchUser(User user, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        //查询到的图书信息
        PageResult pageResult = userService.findAll(user, pageNum, pageSize);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user");
        //将查询到的数据存放在 ModelAndView的对象中
        modelAndView.addObject("pageResult", pageResult);
        //将查询的参数返回到页面，用于回显到查询的输入框中
        modelAndView.addObject("search", user);
        //将当前页码返回到页面，用于分页插件的分页显示
        modelAndView.addObject("pageNum", pageNum);
        //将当前查询的控制器路径返回到页面，页码变化时继续向该路径发送请求
        modelAndView.addObject("gourl", request.getRequestURI());
        return modelAndView;
    }

    /*
    新增用户
     */
    @ResponseBody
    @RequestMapping("/addUser")
    public Result addUser(User user,HttpServletRequest request,
                          @RequestParam("password") String password,
                          @RequestParam("password2") String password2,
                          @RequestParam("email") String email) {
        User u = new User();
        u.setPassword(password);
        u.setPassword2(password2);
        u.setEmail(email);

        if (!u.getPassword().equals(u.getPassword2()) ) {
            return new Result(false, "两次输入密码不一致，新增用户失败!");
        }
        else if(!u.getEmail().matches(
                ("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$")))
        {
            return new Result(false, "邮箱格式错误，新增用户失败!");
        }
        else {
            try {
                Integer count = userService.addUser(user);
                if (count != 1) {
                    return new Result(false, "新增用户失败!");
                }
                return new Result(true, "新增用户成功!");
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "系统错误，新增用户失败!");
            }
        }
    }

    /**
     * 根据图书id查询用户信息
     * @param id 查询
     */
    @ResponseBody
    @RequestMapping("/findById")
    public Result<User> findById(int id) {
        try {
            User user=userService.findUserById(id);
            if(user==null){
                return new Result(false,"查询用户失败！");
            }
            return new Result(true,"查询用户成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"系统错误，查询用户失败！");
        }
    }

    /**
     * 编辑用户信息
     * @param user
     */
    @ResponseBody
    @RequestMapping("/editUser")
    public Result editUser(User user) {
        try {
            Integer count= userService.editUser(user);
            if(count!=1){
                return new Result(false, "编辑失败!");
            }
            return new Result(true, "编辑成功!");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "编辑失败!");
        }
    }

    /**
     * 删除用户信息
     * @param id
     */
    @ResponseBody
    @RequestMapping("/deleteUser")
    public Result deleteUser(@RequestParam("id") int id)
    {
        try{
            Integer count = userService.deleteUser(id);
            if(count != 1){
                return new Result(false, "删除失败!");
            }
            return new Result(true, "删除成功!");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "系统错误，删除失败!");
        }
    }

}
